package xmpp.client.demo;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.X509TrustManager;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.ReconnectionListener;
import org.jivesoftware.smack.ReconnectionManager;
import org.jivesoftware.smack.ReconnectionManager.ReconnectionPolicy;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.SimplePayload;
import org.jxmpp.jid.impl.JidCreate;

/**
 * .
 * @author Caspar
 *
 */
@Slf4j
public class XmppClientPubDemoApplication {


  private static String USRE_NAME = "user44";
  private static String PASSWORD = "user";
  private static String HOST = "im.com";
  private static String XMPP_DOMAIN = "im.com";
  private static String SUBSCRIBE_NODE = "pubsub.test";


  @SneakyThrows
  public static void main(String[] args) {
    //test_sendMsg2();

    // test_sendMsg();

    test_send_pubsub();

  }


  @SneakyThrows
  private static void test_send_pubsub() {
    XMPPTCPConnectionConfiguration connectionConfiguration = XMPPTCPConnectionConfiguration.builder()
        .setHost("im.com")
        .setXmppDomain("im.com")
        .setSecurityMode(SecurityMode.ifpossible)
        .setUsernameAndPassword("user44", "user")

        .setCustomX509TrustManager(new X509TrustManager() {
          @Override
          public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

          }

          @Override
          public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

          }

          @Override
          public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
          }
        })
        .setPort(5222)

        .build();
    XMPPTCPConnection connection = new XMPPTCPConnection(connectionConfiguration);
    connection.addConnectionListener(new ConnectionListener() {
      @Override
      public void connecting(XMPPConnection connection) {
        System.out.println("连接中...");
        ConnectionListener.super.connecting(connection);
      }

      @Override
      public void connected(XMPPConnection connection) {
        System.out.println("连接成功");
        ConnectionListener.super.connected(connection);
      }

      @Override
      public void authenticated(XMPPConnection connection, boolean resumed) {
        System.out.println("连接认证成功");
        ConnectionListener.super.authenticated(connection, resumed);
      }

      @Override
      public void connectionClosed() {
        System.out.println("连接关闭");
        ConnectionListener.super.connectionClosed();
      }

      @Override
      public void connectionClosedOnError(Exception e) {
        System.out.println("连接异常关闭");
        ConnectionListener.super.connectionClosedOnError(e);
      }
    });
    connection.connect();
    connection.login();

    ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection);
    reconnectionManager.setFixedDelay(3);
    reconnectionManager.setReconnectionPolicy(ReconnectionPolicy.FIXED_DELAY);
    reconnectionManager.enableAutomaticReconnection();
    reconnectionManager.addReconnectionListener(new ReconnectionListener() {
      @Override
      public void reconnectingIn(int seconds) {
        System.out.println("重连中...");
      }

      @Override
      public void reconnectionFailed(Exception e) {
        System.out.println("重连失败");
      }
    });
    PubSubManager manager = PubSubManager.getInstanceFor(connection, JidCreate.bareFrom("pubsub.localhost"));

    System.out.println("尝试获取node: ");
    LeafNode eventNode = manager.getLeafNode("test_node.im.com");
    while (true) {
      TimeUnit.SECONDS.sleep(3);
      String itemId = UUID.randomUUID().toString();
      System.out.println("推送消息id: " + itemId);
      SimplePayload payload1 = new SimplePayload("message", "pubsub:cvtalk", "<message xmlns='pubsub:cvtalk'><body>" + itemId + ":消息发布:" + new Date().toString() + "</body></message>");
      PayloadItem<SimplePayload> item1 = new PayloadItem<SimplePayload>(itemId, payload1);
      eventNode.publish(item1);
    }
  }
}
